//
//  LoginController.m
//  DYLYJ
//
//  Created by JM on 15/10/24.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "LoginController.h"
#import "DYUIKit.h"
#import <ReactiveCocoa.h>
#import "DeviceListController.h"
#import "AppDelegate.h"
#import "DYRequestAll.h"
#import "MBProgressHUD.h"
#import "DYArrayDataSource.h"
#import "DYSettingTool.h"
#import "DYUIKit.h"

@interface LoginController ()
@property (strong, nonatomic) JMTextFeiltAutoScroll * autoScroll;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (assign, nonatomic) BOOL loggingIn;
@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"登陆";
//    self.navigationItem.leftBarButtonItem = [UIBarButtonItem backBarItemWithTarget:self action:@selector(clickBack:)];
    self.navigationItem.leftBarButtonItem = nil;
    
    self.tableView.backgroundColor = UIColorFromHexStr(@"#F6F1E8");
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"d"];
//    self.autoScroll = [JMTextFeiltAutoScroll autoScrollWithScrollView:self.tableView];
    
//    RAC(self.loginButton, enabled) = [RACSignal
//                                      combineLatest:@[
//                                                      self.nameTextField.rac_textSignal,
//                                                      self.pwdTextField.rac_textSignal,
//                                                      RACObserve(self, loggingIn),
//                                                      ] reduce:^(NSString *username, NSString *password, NSNumber *
//                                                                 loggingIn) {
//                                                          return @(username.length > 0 && password.length > 0 && !
//                                                          loggingIn.boolValue);
//                                                      }];
    
    
    self.tableView.delaysContentTouches = NO;
    
//    self.nameTextField.text = @"JMTest2";
//    self.pwdTextField.text = @"123456";
    
    self.nameTextField.text = [DYSettingTool objectForKey:DYLoginName];
    
    //自动登录
    self.pwdTextField.text = [DYSettingTool objectForKey:DYLoginPwd];
    if (self.pwdTextField.text.length !=0) {
        [self clickLoginButton:nil];
    }
}

- (void)clickBack:(id) sender {
    [self.view endEditing:YES];
//    //
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.responseSerializer  = [AFJSONResponseSerializer serializer];
////    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    [session GET:@"http://example.com/resources.json" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSLog(@"---成功JSON: %@", responseObject);
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        NSLog(@"---失败：%@",error);
//    }];
    
    //    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    //    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    //
    //    NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"];
    //    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    //
    //    NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
    //    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    //        if (error) {
    //            NSLog(@"Error: %@", error);
    //        } else {
    //            NSLog(@"Success: %@ %@", response, responseObject);
    //        }
    //    }];
    //    [uploadTask resume];
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)clickLoginButton:(id)sender {
    [self.view endEditing:YES];
    if (self.nameTextField.text.length == 0){
        [MJAlertView showMessage:@"请输入用户名"];
        return;
    }
    if (self.pwdTextField.text.length == 0){
        [MJAlertView showMessage:@"请输入密码"];
        return;
    }
    if ([self.nameTextField.text isEqualToString:@"demo"] && [self.pwdTextField.text isEqualToString:@"130130"]){
        myAppDelegate.isDemo = YES;
        myAppDelegate.islogin = YES;
        myAppDelegate.uid = @"demo";
        myAppDelegate.token = @"demo";
        [self dismissViewControllerAnimated:YES completion:^{
        }];
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    LoginRequest *request = [LoginRequest request];
    request.DY_szUserName = self.nameTextField.text;
    request.DY_szPassword = self.pwdTextField.text;
    NSString *name = self.nameTextField.text;
    NSString *pwd = self.pwdTextField.text;
    [request requstWithCompletionHandler:^(DYResponse * rs, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
        LoginResponse *response = (LoginResponse *)rs;
        if (error) {
            [MJAlertView showMessage:@"登陆失败"];
            return ;
        }
        myAppDelegate.islogin = YES;
        myAppDelegate.uid = response.DY_uid;
        myAppDelegate.token = response.DY_token;
        myAppDelegate.isDemo = NO;
        [DYSettingTool setObject:name forKey:DYLoginName];
        [DYSettingTool setObject:pwd forKey:DYLoginPwd];
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 2;
//}
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"d" forIndexPath:indexPath];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
//    cell.textLabel.text = @"dddd";
//    return cell;
//}

//- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
//        [cell setSeparatorInset:UIEdgeInsetsZero];
//    }
//    
//    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//        [cell setLayoutMargins:UIEdgeInsetsZero];
//    }
//    if ([cell respondsToSelector:@selector(tintColor)]) {
//        if (tableView == self.tableView) {
//            CGFloat cornerRadius = 10.f;
//            cell.backgroundColor = UIColor.clearColor;
//            CAShapeLayer *layer = [[CAShapeLayer alloc] init];
//            CGMutablePathRef pathRef = CGPathCreateMutable();
//            CGRect bounds = CGRectInset(cell.bounds, 10, 0);
//            
//            [layer setStrokeColor:tableView.separatorColor.CGColor];
//            [layer setLineWidth:1.f/[UIScreen mainScreen].scale];
//            
//
//            
//            BOOL addLine = NO;
//            if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
//                CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
//            } else if (indexPath.row == 0) {
//                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
//                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
//                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
//                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
//                addLine = YES;
//            } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
//                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
//                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
//                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
//                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
//            } else {
//                CGPathAddRect(pathRef, nil, bounds);
//                addLine = YES;
//            }
//            layer.path = pathRef;
//            
//            layer.borderWidth=2;
//            layer.borderColor = [UIColor redColor].CGColor;
//            CFRelease(pathRef);
//            layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;
//            
//            if (addLine == YES) {
//                CALayer *lineLayer = [[CALayer alloc] init];
//                CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
//                lineLayer.frame = CGRectMake(CGRectGetMinX(bounds), bounds.size.height-lineHeight, bounds.size.width, lineHeight);
//                lineLayer.backgroundColor = tableView.separatorColor.CGColor;
//                [layer addSublayer:lineLayer];
//            }
//            UIView *testView = [[UIView alloc] initWithFrame:bounds];
//            [testView.layer insertSublayer:layer atIndex:0];
//            testView.backgroundColor = UIColor.clearColor;
//            cell.backgroundView = testView;
//        }
//    }
//}

//-(void)viewDidLayoutSubviews
//{
//    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
//        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
//    }
//    
//    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
//        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
//    }
//}
//
//-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
//        [cell setSeparatorInset:UIEdgeInsetsZero];
//    }
//    
//    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
//        [cell setLayoutMargins:UIEdgeInsetsZero];
//    }
//}

//- (BOOL)touchesShouldCancelInContentView:(UIView *)view
//{
//    NSLog(@"touchesShouldCancelInContentView");
//    
//    if ([view isKindOfClass:[UIButton class]])
//        return NO;
//    else
//        return YES;
//}
@end
